<?php
ini_set('display_errors',1);

define('WX_APPID', 'wx927680edc4f2a913');
define('WX_APPSECRET', '70e3a77f5426e36f3a4054565fe85905');


include('./wechat.class.php');

//回调地址
$backurl = $_GET['backurl'];
$scope = array_key_exists('scope',$_GET)?$_GET['scope']:'';
$code = array_key_exists('code',$_GET)?$_GET['code']:null;

if(!$code) {
    if(!in_array($scope,array('base','userinfo'))) {
        die('scope错误');
    }
    //通过服务号的APPID进行授权
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $server= $protocol.$_SERVER['HTTP_HOST'];
    $redirect_uri =$server.$_SERVER['SCRIPT_NAME']."?backurl=".urlencode($backurl);

    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.WX_APPID. '&redirect_uri=' .urlencode($redirect_uri). '&response_type=code&scope=snsapi_'.$scope.'&state=2#wechat_redirect';
    header ( "Location:" . $url );
    die;
}
else{
    $weixin = new wechatOauth(WX_APPID, WX_APPSECRET);
    $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".WX_APPID."&secret=".WX_APPSECRET."&code=".$code."&grant_type=authorization_code";
    $res = $weixin->https_request($url);
    var_dump($res);
    $res = (json_decode($res, true));
    $row = $weixin->get_user_info($res);
    if ($row['openid'] && $backurl) {
        $parms = http_build_query($row);
        if(strpos($backurl,'?')===false){
            header ( "Location:" . $backurl.'?'. $parms);
        }else{
            header ( "Location:" . $backurl.'&'. $parms);
        }
        die;
    }
}

//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe8d99f915b095008&redirect_uri=http%3A%2F%2Fwx.zqgame.com%2Fffffff.php%3Fbackurl%3Dhttp%3A%2F%2Fwx.zqgame.com&response_type=code&scope=snsapi_base&state=2#wechat_redirect
